package cn.parus.auth.service;

import cn.parus.auth.POJO.OpaRequest;
import cn.parus.auth.POJO.DTO.PolicyResult;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @Author: Axel
 * @Description: TODO OPA服务的Service类，已弃用
 **/
@Deprecated
@Service
public class OpaMGService {

    private WebClient webClient;

    public OpaMGService(WebClient opaWebClient) {
        this.webClient = opaWebClient;
    }

    /**
     * 查询策略结果
     * @param opaRequest
     * @return
     */
    public Mono<PolicyResult> checkPermission(OpaRequest opaRequest) {
        return webClient.post()
                .uri("/v1/data/{policyId}/allow",opaRequest.getPolictId())
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(Map.of("input", opaRequest.getPolicyContent()))
                .retrieve()
                .bodyToMono(PolicyResult.class);
    }

    /**
     * 获取OPA服务器的健康信息
     * @return
     */
    public Mono<PolicyResult> opaHealth() {
        return webClient.get()
                .uri("/health")
                .retrieve()
                .bodyToMono(PolicyResult.class);
    }

    /**
     * 根据策略名称查询已经上传的策略
     * @return
     */
    public Mono<PolicyResult> getAllPolicy(OpaRequest opaRequest) {
        return webClient.get()
                .uri("/v1/policies/{policyId}",opaRequest.getPolictId())
                .retrieve()
                .bodyToMono(PolicyResult.class);
    }
}